package com.freemaster.sys.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.freemaster.util.CipherUtil;


@Controller
public class LoginController {

	Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	@Autowired
	CacheManager cacheManager;
	
	@RequestMapping("login")
	public String login(Model model,HttpServletRequest request,HttpServletResponse response){
		logger.info("LoginController--->login--"+request.getParameter("name"));
		
		return "modules/sys/login";
	}
	
	
	
	@RequestMapping("postlogin")
	public String postlogin(Model model,HttpServletRequest request,HttpServletResponse response){
		String result = "login";

		String username = request.getParameter("username");
		 
		//String password = CipherUtil.generatePassword(request.getParameter("password"));
		String password = "d3c59d25033dbf980d29554025c23a75";
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		
		Subject currentUser = SecurityUtils.getSubject();
		try {
			System.out.println("----------------------------");
			if (!currentUser.isAuthenticated()){
				token.setRememberMe(true);
				currentUser.login(token);
			}
			System.out.println("result: " + result);
			result = "loginSu";
			return "redirect:/loginSu";
		} catch (Exception e) {
			logger.error(e.getMessage());
			result = "login";
		}
		return result;
	}
	
	@RequestMapping("loginSu")
	public String loginSu(Model model,HttpServletRequest request,HttpServletResponse response){
		logger.info("LoginController--->loginSu--" );
		
		 PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals(); 
		 
		 logger.info("LoginController--->loginSu--"+principals);
	 
		
		
		return "modules/sys/index";
	}
	
	
    /**
     * 登出
     * @return
     */
    @RequestMapping(value = "/logout")  
    @ResponseBody  
    public String logout() {  
  
        Subject currentUser = SecurityUtils.getSubject();  
        String result = "logout";  
        currentUser.logout();  
        return result;  
    } 
}
